const Mock = require('mockjs');

// 生成随机整数
const randomInt = (min, max) => {
  const intMin = Math.ceil(min);
  const intMax = Math.floor(max);
  return Math.floor(Math.random() * (intMax - intMin + 1)) + intMin;
};

// 生成随机浮点数（保留指定位数）
const randomFloat = (min, max, fixed) =>
  parseFloat((Math.random() * (max - min) + min).toFixed(fixed));

// 生成节假日通用数据
const generateHolidayData = () => ({
  revenue: randomInt(100000, 250000),
  profit: randomInt(30000, 100000),
  orderCount: randomInt(800, 2000),
  customerFlow: randomInt(1000, 3000),
  revenueGrowth: `${randomFloat(10, 50, 1)}%`,
  roi: randomFloat(1, 5, 2).toString(),
  newCustomerRatio: `${randomFloat(15, 40, 1)}%`
});

// 生成评分数据
const generateRating = () => {
  const rawValue = randomFloat(3.5, 5.0, 2);
  return Math.min(5.0, rawValue).toFixed(1)
};


// 生成开业日期
const generateOpeningDate = () => {
  // 定义时间范围
  const startDate = new Date('2015-01-01').getTime();
  const endDate = new Date('2023-12-31').getTime();
  // 生成随机时间戳
  const randomTimestamp = randomInt(startDate, endDate);
  // 格式化为日期字符串
  return new Date(randomTimestamp).toISOString().split('T')[0];
};

// 基本信息
const generateBasicData = () => {
  const fullCity = Mock.Random.city(true);
  const [province, city] = fullCity.split(' ');

  return {
    storeId: Math.floor(100000000 + Math.random() * 900000000).toString(),
    storeName: `${province}${city}${['分', '东', '南', '西', '北', '一', '二', '三', '四', '五'].at(randomInt(0, 9))}店`,
    province: province,
    city: city,
    coordinates: {
      lng: randomFloat(105.0, 123.0, 4).toString(),
      lat: randomFloat(20.0, 40.0, 4).toString()
    },
    storeType: ['直营', '加盟'].at(randomInt(0, 1)),
    areaSize: randomInt(80, 300),
    openingDate: generateOpeningDate(),
    tags: [['商业区', '社区', '学校', '景区', '交通枢纽'].at(randomInt(0, 4))]
  }
}


const generateStoreData = (storeInfo) => {

  // 生成每日数据
  const generateDailyData = () => {
    const baseSales = randomInt(30000, 80000);
    const startDate = new Date('2024-01-01');

    return Array.from({ length: 366 }, (_, index) => {
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + index);

      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');

      return {
        date: `${year}-${month}-${day}`,
        revenue: {
          amount: randomInt(baseSales * 0.9, baseSales * 1.1),
          yoy: `${randomFloat(-5, 15, 1)}%`,
          mom: `${randomFloat(-8, 10, 1)}%`,
          target: baseSales
        },
        profit: randomInt(8000, 35000),
        orderCount: randomInt(150, 600),
        customerFlow: randomInt(200, 800)
      };
    });
  };

  // 生成月度数据
  const generateMonthlyData = () =>
    Array.from({ length: 12 }, (_, month) => ({
      month: month + 1,
      costs: {
        total: randomInt(200000, 800000),
        ingredients: randomInt(80000, 300000),
        labor: randomInt(50000, 200000),
        operation: randomInt(30000, 150000),
        energy: randomInt(10000, 50000),
        maintenance: randomInt(5000, 30000),
        financial: randomInt(10000, 80000)
      },
      membership: {
        consumptionRatio: `${randomFloat(20, 60, 1)}%`,
        newMembers: randomInt(50, 300),
        repurchaseRate: `${randomFloat(15, 45, 1)}%`
      },
      deliveryRatio: `${randomFloat(15, 55, 1)}%`,
      staffEfficiency: randomFloat(500, 2000, 0).toString(),
      areaEfficiency: randomFloat(50, 200, 1).toString(),
      tableTurnover: randomFloat(1.5, 4.5, 1).toString(),
      staffCount: randomInt(8, 20)
    }));

  // 生成年度数据
  const generateAnnualData = () => ({
    promotions: {
      springFestival: generateHolidayData(),
      laborDay: generateHolidayData(),
      nationalDay: generateHolidayData(),
      summer: generateHolidayData()
    },
    avgCustomerValue: randomInt(35, 85),
    rating: generateRating(),
    reviews: {
      positive: randomInt(500, 2000),
      negative: randomInt(0, 50)
    },
    yearGrowth: `${randomFloat(4, 9, 1)}%`
  });

  // 赋值到目标对象
  storeInfo.basicInfo = generateBasicData();
  storeInfo.dailyData = generateDailyData();
  storeInfo.monthlyData = generateMonthlyData();
  storeInfo.annualData = generateAnnualData();


  //月营业额
  // 初始化按月营业额汇总对象
  const monthlyRevenue = {};
  // 计算各月营业额总和
  storeInfo.dailyData.forEach((day) => {
    const month = parseInt(day.date.split('-')[1], 10); // 提取月份数字
    monthlyRevenue[month] = (monthlyRevenue[month] || 0) + day.revenue.amount;
  });
  // 将月营业额添加到monthlyData
  storeInfo.monthlyData.forEach((monthData) => {
    monthData.totalRevenue = monthlyRevenue[monthData.month] || 0;
  });

  // 年营业额
  // const sum = storeInfo.dailyData.reduce((acc: any, day: any) => {
  //   return acc + (day.revenue.amount || 0)
  // }, 0)

  // 年营业额计算
  const annualSum = storeInfo.monthlyData.reduce((sum, m) => sum + m.totalRevenue, 0);
  storeInfo.annualData.yearAmount = annualSum

  return storeInfo;
};

// 批量生成并保存
const generateStores = (count = 20) => {
  console.time('Data generation completed');
  const stores = Array.from({ length: count }, (_, i) => {
    if ((i + 1) % 100 === 0) console.log(`Generated ${i + 1} records`);
    return generateStoreData({});
  });
  console.timeEnd('Data generation completed');
  return stores;
};

// 保存到文件
const fs = require('fs');
fs.writeFileSync('fullStores.json',
  JSON.stringify(generateStores(), null, 2));
console.log('Data saved to stores.json');